
package com.aris.voicechecking;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.PowerManager;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.voicecheck.provider.DataProviderV2;
import com.voicecheck.util.StringUtil;
import com.voicecheck.v2.model.LessonModel;
import com.voicecheck.v2.model.SentencesModel;
import com.voicecheck.v2.model.UrlModel;

public class LessonDetailActivity extends ActionBarActivity implements OnCompletionListener,
OnPreparedListener {

    protected UrlModel urlModel;

    protected ImageView micro;

    protected ImageView status_answer;

    private TextView txtSpeechInput;

    private TextView lesson_title; // lesson title or topic

    private TextView actionbar_title; // actionbar title week - day - (1-1)

    private int current_index_lesson; // current stt lesson learning

    private int daynumber; // day

    private int weeknumber; // week

    private SeekBar timeoutbar; // seekbar

    private SpeechRecognizer speech = null;

    private Intent recognizerIntent;

    private DataProviderV2 dataConnection; // connect database

    private List<LessonModel> listLesson; // list lesson ( 6 is default)

    private LessonModel current_lession; // current lesson user is learning

    private ImageView lesson_cover; // cover of lesson

    private MediaPlayer player;

    // private int font_size;

    private ImageView checking_result;

    private ImageView back_previous_lesson;

    private ImageView goto_next_lesson;

    private CountDownTimer countdownTimer;

    private int counter;

    private TextView seekbar_duration_decreament;

    private TextView seekbar_duration_increament;

    private SharedPreferences reference;

    private LinearLayout list_sentences_bounder;

    private int sequence_of_sentences;

    private List<SentencesModel> sentences;

    private Boolean isSpeaking;

    private ScrollView scrollview;

    private Boolean pauseState;

    private String regex = "#";

    private Boolean recognizing;

    private ProgressDialog waitingDialog;

    private Boolean windowHasFocus;

    protected int firstVoice;

    protected int time = 15;

    protected String person_name;

    protected String bufferUserInput;

    protected Boolean allowTry;

    protected int seLesson;

    static enum MIC_STATE {
        STATE_NONE, STATE_MICRO, STATE_SPEAKER, STATE_DONE
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson_detail);

        initital();
        execution();

    }

    private void initital() {

        seLesson = getIntent().getExtras().getInt("se");

        windowHasFocus = false;
        reference = getSharedPreferences(getString(R.string.user_data), Context.MODE_PRIVATE);

        micro = (ImageView)findViewById(R.id.ic_micro);
        txtSpeechInput = (TextView)findViewById(R.id.txtSpeechInput);
        daynumber = getIntent().getExtras().getInt("daynumber");
        weeknumber = getIntent().getExtras().getInt("weeknumber");
        timeoutbar = (SeekBar)findViewById(R.id.timeoutbar);
        timeoutbar.setMax(150);
        // initial recognizer

        dataConnection = new DataProviderV2(this);
        lesson_cover = (ImageView)findViewById(R.id.lesson_cover);
        lesson_title = (TextView)findViewById(R.id.lesson_title);
        current_index_lesson = 0;
        checking_result = (ImageView)findViewById(R.id.checking_result);
        back_previous_lesson = (ImageView)findViewById(R.id.back_previous_lesson);
        goto_next_lesson = (ImageView)findViewById(R.id.goto_next_lesson);
        counter = 0;
        seekbar_duration_decreament = (TextView)findViewById(R.id.seekbar_duration);
        seekbar_duration_increament = (TextView)findViewById(R.id.time_begin);

        urlModel = dataConnection.retrieveURLByID(reference.getLong(
                getString(R.string.user_data_connect_link), 1));
        list_sentences_bounder = (LinearLayout)findViewById(R.id.list_sentences);
        isSpeaking = false;
        scrollview = (ScrollView)findViewById(R.id.scrollview);

    }

    @Override
    protected void onPause() {
        super.onPause();

        PowerManager manager = (PowerManager)getSystemService(Context.POWER_SERVICE);
        @SuppressWarnings("deprecation")
        Boolean screen_off = manager.isScreenOn();

        Log.d("LessonDetailActivity", screen_off.toString());

        pauseState = true;
        try {
            if (speech != null) {

                speech.stopListening();
                speech.cancel();
                speech.destroy();
            }
        } catch (Exception e) {

        }

        if (player != null) {
            player.stop();
            player.reset();
            player.release();
            player = null;
        }

        if (firstVoice < 2 || current_lession.getAnswered())
            list_sentences_bounder.removeAllViews();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.drawable.anim_slide_in_right, R.drawable.anim_slide_out_right);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        if (!windowHasFocus && hasFocus) {
            startLesson();
            windowHasFocus = hasFocus;
        }

        if (pauseState == true)
            windowHasFocus = hasFocus;
    }

    @Override
    protected void onResume() {
        super.onResume();

        pauseState = false;

        speech = SpeechRecognizer.createSpeechRecognizer(this);
        speech.setRecognitionListener(recognizeListener);
        recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.US.toString());
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, Locale.US.toString());
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE,
                Locale.US.toString());
        recognizerIntent.putExtra("android.speech.extra.EXTRA_ADDITIONAL_LANGUAGES", new String[] {
                "en"
        });

        recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);

        if (micro != null) {
            if (micro.getTag() == MIC_STATE.STATE_SPEAKER)
                micro.setImageResource(R.drawable.ico_speark);
        }

        loadingLesson();

        if (windowHasFocus)
            startLesson();
    }

    private void execution() {

        if (seLesson > 0) {
            back_previous_lesson.setVisibility(View.GONE);
            goto_next_lesson.setVisibility(View.GONE);
        }

        config_actionbar();
        config_fontSize();
        config_seekbar();
        config_lesson_mic();
        config_other();

    }

    private void config_other() {

        back_previous_lesson.setOnClickListener(onBackClick);
        goto_next_lesson.setOnClickListener(onNextClick);

    }

    private void loadingLesson() {

        allowTry = false;
        recognizing = false;
        micro.setImageResource(R.drawable.ico_mic_enable_disable);
        micro.setTag(MIC_STATE.STATE_NONE);
        current_lession = listLesson.get(current_index_lesson);

        if (seLesson == 0)
            actionbar_title.setText(getString(R.string.week) + weeknumber + " - "
                    + getString(R.string.day) + daynumber + " ("
                    + (current_index_lesson >= 3 ? 2 : 1) + "-" + (current_index_lesson % 3 + 1)
                    + ")");
        else
            actionbar_title.setText(getString(R.string.week) + weeknumber + " - "
                    + getString(R.string.day) + daynumber + " (" + ((seLesson - 1) >= 3 ? 2 : 1)
                    + "-" + ((seLesson - 1) % 3 + 1) + ")");

        lesson_title.setText(current_lession.getSubject());

        String path = urlModel.getDir() + "/image/" + current_lession.getCover_image();

        if (firstVoice < 2)
            list_sentences_bounder.removeAllViews();

        Drawable d = Drawable.createFromPath(path);
        lesson_cover.setImageDrawable(d);
        sentences = current_lession.getSentences();
        if (status_answer != null) {
            if (current_lession.getDone() == 1)
                status_answer.setImageResource(R.drawable.btn_ok);
            else
                status_answer.setImageResource(R.drawable.btn_try);
        }

        if (seLesson == 0) {
            back_previous_lesson.setVisibility(View.VISIBLE);
            back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
            back_previous_lesson.setEnabled(false);

            goto_next_lesson.setImageResource(R.drawable.btq_next_disible);
            goto_next_lesson.setVisibility(View.VISIBLE);
            goto_next_lesson.setEnabled(false);
        }

    }

    private void startLesson() {

        if (!current_lession.getAnswered()) {
            loadNewQuestion();
        } else {
            loadAnsweredQuestion();
            micro.setTag(MIC_STATE.STATE_SPEAKER);
        }

    }

    private void loadAnsweredQuestion() {

        if (seLesson == 0) {
            goto_next_lesson.setImageResource(R.drawable.btq_next);
            goto_next_lesson.setEnabled(true);

            if (current_index_lesson == 0) {
                // back_previous_lesson.setVisibility(View.GONE);
                back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                back_previous_lesson.setEnabled(false);
            } else {
                back_previous_lesson.setVisibility(View.VISIBLE);
                back_previous_lesson.setImageResource(R.drawable.btq_previous);
                back_previous_lesson.setEnabled(true);
            }
        } else {
            goto_next_lesson.setVisibility(View.GONE);
            back_previous_lesson.setVisibility(View.GONE);
        }

        micro.setImageResource(R.drawable.ico_speark);
        timeoutbar.setProgress(150);
        seekbar_duration_decreament.setText("00:00");
        seekbar_duration_increament.setText("00:" + time);
        txtSpeechInput.setText(current_lession.getAnswered_str());
        checking_result.setVisibility(View.VISIBLE);

        if (current_lession.getLast_done() == 1) {
            checking_result.setImageResource(R.drawable.popup_true);

            for (int i = 0; i < sentences.size(); i++) {
                sequence_of_sentences = i;
                drawSentences();
            }
        } else {

            checking_result.setImageResource(R.drawable.popup_false);
            for (int i = 0; i < sentences.size(); i++) {
                if (i > 0 && sentences.get(i - 1).getRecognize().equals("TRUE"))
                    break;
                sequence_of_sentences = i;
                drawSentences();
            }
        }

    }

    private void loadNewQuestion() {

        if (firstVoice == 2) {

            if (seLesson == 0) {
                if (current_index_lesson != 0) {
                    back_previous_lesson.setVisibility(View.VISIBLE);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous);
                    back_previous_lesson.setEnabled(true);
                } else {
                    // back_previous_lesson.setVisibility(View.GONE);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                    back_previous_lesson.setEnabled(false);
                }

                // goto_next_lesson.setVisibility(View.VISIBLE);
                goto_next_lesson.setEnabled(true);
                goto_next_lesson.setImageResource(R.drawable.btq_next);
            } else {
                back_previous_lesson.setVisibility(View.GONE);
                goto_next_lesson.setVisibility(View.GONE);
            }

            for (int i = 0; i < sentences.size(); i++) {
                if (sentences.get(i).getRecognize().equals("TRUE")) {
                    sequence_of_sentences = i;
                    break;
                }
            }

            micro.setImageResource(R.drawable.ico_mic_enable);
            micro.setTag(MIC_STATE.STATE_MICRO);

            return;
        }

        firstVoice = 1;
        checking_result.setVisibility(View.GONE);

        timeoutbar.setProgress(0);
        seekbar_duration_decreament.setText("00:" + time);
        seekbar_duration_increament.setText("00:00");
        sequence_of_sentences = 0;
        txtSpeechInput.setText("");

        (new Handler()).postDelayed(new Runnable() {

            @Override
            public void run() {
                playAudio();
            }

        }, 1000);
    }

    private void config_lesson_mic() {

        if (seLesson == 0) {
            listLesson = dataConnection.retrieveLessonByDay(weeknumber, daynumber);
        } else {
            listLesson = dataConnection.retrieveLessonByLesson(weeknumber, daynumber, seLesson);
        }

        Log.d("lession------------->", listLesson.size() + "");

        micro.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                MIC_STATE micstate = (MIC_STATE)arg0.getTag();

                switch (micstate) {
                    case STATE_NONE:
                        break;
                    case STATE_MICRO:
                        if (!hasConnection()) {
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(
                                    LessonDetailActivity.this);
                            builder1.setMessage(getString(R.string.offline_mode));
                            builder1.setCancelable(false);
                            builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {

                                    dialog.cancel();

                                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                                        startAnswering();
                                    }

                                }
                            });

                            AlertDialog alert11 = builder1.create();

                            alert11.show();
                            return;
                        }
                        firstVoice = 1;
                        startAnswering();
                        break;
                    case STATE_DONE:

                        if (recognizing) {

                            waitingDialog = ProgressDialog.show(LessonDetailActivity.this, "",
                                    getString(R.string.waiting));

                            // do nothing .. and show progressdialog
                        } else {

                            micro.setTag(MIC_STATE.STATE_NONE);
                            countdownTimer.cancel();
                            speech.stopListening();
                            timeoutbar.setProgress(time * 10);
                            seekbar_duration_decreament.setText("00:00");
                            seekbar_duration_increament.setText("00:" + time);
                            // micro.setImageResource(R.drawable.ico_mic);
                            checkingResult();
                        }
                        break;
                    case STATE_SPEAKER:

                        back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                        back_previous_lesson.setEnabled(false);

                        goto_next_lesson.setImageResource(R.drawable.btq_next_disible);
                        goto_next_lesson.setEnabled(false);

                        micro.setImageResource(R.drawable.ico_speark_pause);
                        if (isSpeaking)
                            return;
                        isSpeaking = true;

                        if (player != null)
                            player.reset();
                        else {
                            player = new MediaPlayer();
                            player.setOnCompletionListener(LessonDetailActivity.this);
                            player.setOnPreparedListener(LessonDetailActivity.this);
                            player.setVolume(1f, 1f);
                            player.setLooping(false);
                        }

                        try {
                            for (int i = 0; i < sentences.size(); i++) {
                                if (sentences.get(i).getRecognize().equals("TRUE")) {
                                    FileInputStream stream = new FileInputStream(urlModel.getDir()
                                            + "/audio/" + sentences.get(i).getAudio_name());
                                    player.setDataSource(stream.getFD());
                                    stream.close();
                                    player.prepare();
                                    break;
                                }
                            }

                        } catch (Exception e) {

                        }

                        break;

                    default:
                        break;
                }

            }

        });

    }

    private void startAnswering() {

        speech.startListening(recognizerIntent);
        // goto_next_lesson.setVisibility(View.GONE);

        if (seLesson == 0) {
            goto_next_lesson.setImageResource(R.drawable.btq_next_disible);
            goto_next_lesson.setEnabled(false);

            // back_previous_lesson.setVisibility(View.GONE);
            back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
            back_previous_lesson.setEnabled(false);
        } else {
            goto_next_lesson.setVisibility(View.GONE);
            back_previous_lesson.setVisibility(View.GONE);
        }

        micro.setTag(MIC_STATE.STATE_NONE);

        micro.setImageResource(R.drawable.ico_mic_enable_disable);

        counter = 0;

        startCountDownTimer();
    }

    public void startCountDownTimer() {
        countdownTimer = new CountDownTimer(15000, 100) {

            @Override
            public void onTick(long millisUntilFinished) {
                counter++;
                String str = (time - (counter / 10)) + "";
                String str2 = counter / 10 + "";

                Log.e("------------------time", counter + "," + counter / 10);

                if (counter >= 15) {
                    micro.setTag(MIC_STATE.STATE_DONE);
                    micro.setImageResource(R.drawable.ico_mic);
                }

                seekbar_duration_decreament.setText("-00:" + (str.length() == 2 ? "" : "0") + str);

                seekbar_duration_increament.setText("00:" + (str2.length() == 2 ? "" : "0")
                        + counter / 10);
                timeoutbar.setProgress(counter);

            }

            @Override
            public void onFinish() {

                if (recognizing) {

                    if (waitingDialog != null && !waitingDialog.isShowing())
                        waitingDialog.show();

                } else {
                    speech.stopListening();
                    timeoutbar.setProgress(time * 10);
                    seekbar_duration_decreament.setText("00:00");
                    seekbar_duration_increament.setText("00:" + time);
                    // micro.setImageResource(R.drawable.ico_mic);
                    checkingResult();
                }

            }
        };

        countdownTimer.start();
    }

    public void checkingResult() {
        String userSpeakText = txtSpeechInput.getText().toString().toLowerCase(Locale.ENGLISH)
                .trim();

        if (userSpeakText.equals("")) {
            userSpeakText = bufferUserInput;
        }

        if (userSpeakText == null)
            userSpeakText = "";

        userSpeakText = userSpeakText.replaceAll("[^a-zA-Z0-9]", "");

        Log.v("User speaking text : ", "-" + userSpeakText + "-" + userSpeakText.length());

        String resultText = sentences.get(sequence_of_sentences).getQuestion_content()
                .toLowerCase(Locale.ENGLISH).trim();

        if (checkAnswer(userSpeakText, resultText.split(regex))) {

            SharedPreferences sharedpreferences = getSharedPreferences(
                    getString(R.string.user_data), Context.MODE_PRIVATE);

            Editor editor = sharedpreferences.edit();
            editor.putInt(getString(R.string.update_lesson_result), seLesson);
            editor.commit();

            status_answer.setImageResource(R.drawable.btn_ok);
            checking_result.setImageResource(R.drawable.popup_true);

            if (current_lession.getDone() == 0) {
                dataConnection.updateLessonDone(current_lession.getId());
            }

            current_lession.setDone(1);
            current_lession.setLast_done(1);
            dataConnection.updateHistoryLessonLastDone(current_lession.getWeek(),
                    current_lession.getDay(), current_lession.getLesson());

            drawSentences();

            sequence_of_sentences += 1;
            playAudio();

        } else {
            checking_result.setImageResource(R.drawable.popup_false);
            current_lession.setLast_done(0);
            dataConnection.updateHistoryLessonLastFail(current_lession.getWeek(),
                    current_lession.getDay(), current_lession.getLesson());

            micro.setTag(MIC_STATE.STATE_SPEAKER);
            micro.setImageResource(R.drawable.ico_speark);

            if (seLesson == 0) {
                if (current_index_lesson != 0) {
                    back_previous_lesson.setVisibility(View.VISIBLE);
                    back_previous_lesson.setEnabled(true);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous);
                } else {
                    back_previous_lesson.setVisibility(View.VISIBLE);
                    back_previous_lesson.setEnabled(false);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                }

                goto_next_lesson.setVisibility(View.VISIBLE);
                goto_next_lesson.setEnabled(true);
                goto_next_lesson.setImageResource(R.drawable.btq_next);
            } else {
                goto_next_lesson.setVisibility(View.GONE);
                back_previous_lesson.setVisibility(View.GONE);
            }

            drawSentences();
            allowTry = false;

        }

        current_lession.setAnswered_str(txtSpeechInput.getText().toString());
        current_lession.setAnswered(true);

    }

    protected Boolean checkAnswer(String userinput, String[] answers) {

        for (int i = 0; i < answers.length; i++) {

            String answer = answers[i];
            answer = answer.replaceAll("[^a-zA-Z0-9]", "");
            Log.v("Result text :", "-" + userinput + "-" + userinput.length());
            checking_result.setVisibility(View.VISIBLE);

            // String name = StringUtil.checkPersonName(answer,
            // getApplicationContext());

            if (person_name == null || person_name.equals("")) {
                if (userinput.equals(answer))
                    return true;
            } else {
                if (checkAnswerWithPersonName(userinput, answer, person_name)) {
                    if (answers.length > 0) {

                        txtSpeechInput.setText(answers[0].replaceAll("[^a-zA-Z0-9 ]", ""));
                    }
                    person_name = "";
                    return true;
                } else {

                    txtSpeechInput.setText(bufferUserInput);
                    person_name = "";

                }

            }

        }

        return false;
    }

    protected Boolean checkAnswerWithPersonName(String userinput, String answer, String name) {

        int front = answer.indexOf(name);
        int back = answer.length() - front - name.length();

        if (userinput.length() < back || userinput.length() < front)
            return false;

        if (userinput.substring(0, front - 1).equals(answer.substring(0, front - 1))
                && userinput.substring(userinput.length() - back, userinput.length()).equals(
                        answer.substring(answer.length() - back, answer.length()))) {
            return true;
        }

        return false;
    }

    protected void config_seekbar() {
        timeoutbar.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.performClick();
                return true;
            }
        });
    }

    OnClickListener onBackClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            speech.stopListening();

            if (player != null)
                player.stop();

            current_index_lesson -= 1;

            if (current_index_lesson < 0)
                current_index_lesson = 0;

            if (current_index_lesson == 0) {
                back_previous_lesson.setVisibility(View.VISIBLE);
                back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                back_previous_lesson.setEnabled(false);
            } else {
                back_previous_lesson.setVisibility(View.VISIBLE);
                back_previous_lesson.setImageResource(R.drawable.btq_previous);
                back_previous_lesson.setEnabled(true);
            }

            final ProgressDialog dialog = ProgressDialog.show(LessonDetailActivity.this, "",
                    getString(R.string.next_question));// + " (" +
            // (current_index_lesson
            // >= 3 ? 2 : 1)
            // + "-" + (current_index_lesson % 3 + 1) + ")");

            (new Handler()).postDelayed(new Runnable() {

                @Override
                public void run() {

                    current_lession = listLesson.get(current_index_lesson);
                    firstVoice = 1;
                    loadingLesson();
                    startLesson();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });

                }
            }, 1000);

        }
    };

    OnClickListener onNextClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            speech.stopListening();

            if (player != null)
                player.stop();

            current_index_lesson += 1;
            if (current_index_lesson >= listLesson.size()) {

                Intent reportIntent = new Intent(LessonDetailActivity.this, DayReportActivity.class);

                String done_status = "";
                String pass_status = "";

                for (LessonModel nlesson : listLesson) {
                    if (nlesson.getAnswered()) {
                        if (nlesson.getLast_done() == 1) {
                            pass_status += "0";
                        } else {
                            pass_status += "x";
                        }

                    } else {
                        pass_status += "-";
                    }
                }

                for (LessonModel nlesson : listLesson) {
                    if (nlesson.getDone() == 1) {
                        done_status += "1";
                    } else {
                        done_status += "0";
                    }
                }

                reportIntent.putExtra("done_status", done_status);
                reportIntent.putExtra("pass_status", pass_status);
                reportIntent.putExtra("weeknumber", weeknumber);
                reportIntent.putExtra("daynumber", daynumber);

                startActivity(reportIntent);

                finish();

                return;
            }

            final ProgressDialog dialog = ProgressDialog.show(LessonDetailActivity.this, "",
                    getString(R.string.next_question));
            // + " (" +
            // (current_index_lesson
            // >= 3 ? 2 : 1)
            // + "-" + (current_index_lesson % 3 + 1) + ")");

            (new Handler()).postDelayed(new Runnable() {

                @Override
                public void run() {

                    // current_lession = listLesson.get(current_index_lesson);
                    firstVoice = 1;
                    loadingLesson();
                    startLesson();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });

                }
            }, 1000);

        }
    };

    // private void config_text_input() {
    // txtSpeechInput.setTextSize(TypedValue.COMPLEX_UNIT_SP, font_size);
    // }

    private void config_fontSize() {
        txtSpeechInput.setTextSize(18);
        (new Handler()).postDelayed(new Runnable() {

            @Override
            public void run() {
                Paint paint = new Paint();
                // float density = getResources().getDisplayMetrics().density;
                paint.setTextSize(txtSpeechInput.getTextSize());

                Rect bounds = new Rect();
                paint.getTextBounds("123456789123456789121", 0, 21, bounds);

                float w = bounds.width();
                float wofview = txtSpeechInput.getMeasuredWidth();
                float padding = (wofview - w) / 2;
                txtSpeechInput.setPadding((int)padding, 15, (int)padding, 15);
                // config_text_input();

            }
        }, 500);

    }

    private void config_actionbar() {

        ActionBar actionBar = getSupportActionBar();
        ColorDrawable colorDrawable = new ColorDrawable(getResources().getColor(R.color.main_color));
        actionBar.setBackgroundDrawable(colorDrawable);

        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);

        View actionbarcustomeview = getLayoutInflater().inflate(R.layout.actionbar_center_title,
                (ViewGroup)(getSupportActionBar().getCustomView()));

        actionbar_title = (TextView)actionbarcustomeview.findViewById(R.id.center_title);

        actionbar_title.setTextColor(Color.WHITE);

        actionBar.setCustomView(actionbarcustomeview, new ActionBar.LayoutParams(
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.CENTER));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.lesson_detail, menu);

        MenuItem menuItem = menu.findItem(R.id.status_button);

        status_answer = (ImageView)MenuItemCompat.getActionView(menuItem);
        status_answer.setImageResource(R.drawable.btn_try);
        status_answer.setPadding(10, 10, 20, 10);

        if (current_lession.getDone() != 0) {
            status_answer.setImageResource(R.drawable.btn_ok);
        } else {
            status_answer.setImageResource(R.drawable.btn_try);
        }

        status_answer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (allowTry)
                    return;

                if (!current_lession.getAnswered())
                    return;

                if (current_lession.getDone() != 0) {
                    // Toast.makeText(LessonDetailActivity.this, "Done",
                    // Toast.LENGTH_SHORT).show();
                } else {

                    allowTry = true;
                    txtSpeechInput.setText("");

                    if (!hasConnection()) {
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(
                                LessonDetailActivity.this);
                        builder1.setMessage(getString(R.string.offline_mode));
                        builder1.setCancelable(false);
                        builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {

                                dialog.cancel();

                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                                    startAnswering();
                                }

                            }
                        });

                        AlertDialog alert11 = builder1.create();

                        alert11.show();
                        return;
                    }
                    firstVoice = 1;
                    startAnswering();
                }
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    RecognitionListener recognizeListener = new RecognitionListener() {

        @Override
        public void onRmsChanged(float rmsdB) {

        }

        @Override
        public void onResults(Bundle results) {

            if (micro.getTag() == MIC_STATE.STATE_SPEAKER) {
                return;
            }

            micro.setTag(MIC_STATE.STATE_DONE);
            micro.setImageResource(R.drawable.ico_mic);

            Log.i(this.getClass().toString(), "onResults");
            ArrayList<String> matches = results
                    .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

            if (matches.size() == 0)
                txtSpeechInput.setText("");

            String str_result = matches.get(0);

            if (str_result.length() >= 60)
                str_result = str_result.subSequence(0, 59).toString();

            person_name = StringUtil.checkPersonName(sentences.get(sequence_of_sentences)
                    .getQuestion_content().toLowerCase(Locale.ENGLISH).trim(),
                    getApplicationContext());

            if (person_name.equals(""))
                txtSpeechInput.setText(str_result);
            else
                bufferUserInput = str_result;

            Log.d("Speech to text", "Result of speech ..............'" + str_result + "'");

            recognizing = false;

            if (!txtSpeechInput.equals("")) {

                if (waitingDialog != null && waitingDialog.isShowing()) {
                    waitingDialog.dismiss();
                }

                micro.setTag(MIC_STATE.STATE_NONE);
                countdownTimer.cancel();
                speech.stopListening();
                timeoutbar.setProgress(time * 10);
                seekbar_duration_decreament.setText("00:00");
                seekbar_duration_increament.setText("00:" + time);

                checkingResult();
            }

        }

        @Override
        public void onReadyForSpeech(Bundle params) {
            Log.d("Google now", "Ready For Speech - " + recognizing);
        }

        @Override
        public void onPartialResults(Bundle partialResults) {
            Log.d("Google now", "Partial Result - " + recognizing);
        }

        @Override
        public void onEvent(int eventType, Bundle params) {
            Log.d("Google now", "Event - " + recognizing);
        }

        @Override
        public void onError(int error) {
            Log.d("Google now", "Error - " + recognizing);

            if (!recognizing)
                return;

            recognizing = false;
            bufferUserInput = "";
            person_name = "";
            txtSpeechInput.setText("");

            micro.setTag(MIC_STATE.STATE_NONE);
            countdownTimer.cancel();
            speech.stopListening();
            timeoutbar.setProgress(time * 10);
            seekbar_duration_decreament.setText("00:00");
            seekbar_duration_increament.setText("00:" + time);

            if (waitingDialog != null && waitingDialog.isShowing()) {
                waitingDialog.dismiss();
            }

            checkingResult();
        }

        @Override
        public void onEndOfSpeech() {
            Log.d("Google now", "End of Speech - " + recognizing);
            // recognizing = false;

        }

        @Override
        public void onBufferReceived(byte[] buffer) {
            Log.d("Google now", "Buffer Received - " + recognizing);

        }

        @Override
        public void onBeginningOfSpeech() {

            Log.d("Speech to text", "Begin of speech ..............- " + recognizing);

            recognizing = true;

        }
    };

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (micro.getTag() == MIC_STATE.STATE_SPEAKER) {
            micro.setImageResource(R.drawable.ico_speark);
            isSpeaking = false;

            if (seLesson == 0) {
                if (current_index_lesson == 0) {
                    // back_previous_lesson.setVisibility(View.GONE);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                    back_previous_lesson.setEnabled(true);
                } else {
                    back_previous_lesson.setVisibility(View.VISIBLE);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous);
                    back_previous_lesson.setEnabled(true);
                }

                goto_next_lesson.setImageResource(R.drawable.btq_next);
                goto_next_lesson.setEnabled(true);
            } else {
                goto_next_lesson.setVisibility(View.GONE);
                back_previous_lesson.setVisibility(View.GONE);
            }

            return;
        }

        if (seLesson == 0) {
            if (current_index_lesson == 0) {
                // back_previous_lesson.setVisibility(View.GONE);
                back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                back_previous_lesson.setEnabled(true);
            } else {
                back_previous_lesson.setVisibility(View.VISIBLE);
                back_previous_lesson.setImageResource(R.drawable.btq_previous);
                back_previous_lesson.setEnabled(true);
            }

            goto_next_lesson.setImageResource(R.drawable.btq_next);
            goto_next_lesson.setEnabled(true);
        } else {
            goto_next_lesson.setVisibility(View.GONE);
            back_previous_lesson.setVisibility(View.GONE);
        }

        sequence_of_sentences += 1;
        if (sequence_of_sentences < sentences.size()
                && sentences.get(sequence_of_sentences).getRecognize().equals("TRUE")) {
            // micro.setImageResource(R.drawable.ico_mic);
            firstVoice = 2;
            micro.setImageResource(R.drawable.ico_mic_enable);
            micro.setTag(MIC_STATE.STATE_MICRO);

        } else {

            if (seLesson == 0) {
                back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                back_previous_lesson.setEnabled(false);

                goto_next_lesson.setImageResource(R.drawable.btq_next_disible);
                goto_next_lesson.setEnabled(false);
            } else {
                goto_next_lesson.setVisibility(View.GONE);
                back_previous_lesson.setVisibility(View.GONE);
            }
            playAudio();
        }
    }

    @Override
    public void onPrepared(MediaPlayer arg0) {

        if (pauseState) {
            arg0.stop();
            return;
        }

        arg0.start();

    }

    protected void playAudio() {

        if (sequence_of_sentences >= sentences.size()) {
            if (seLesson == 0) {
                if (current_index_lesson != 0) {
                    back_previous_lesson.setVisibility(View.VISIBLE);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous);
                    back_previous_lesson.setEnabled(true);
                } else {
                    // back_previous_lesson.setVisibility(View.GONE);
                    back_previous_lesson.setImageResource(R.drawable.btq_previous_disible);
                    back_previous_lesson.setEnabled(false);
                }

                // goto_next_lesson.setVisibility(View.VISIBLE);
                goto_next_lesson.setEnabled(true);
                goto_next_lesson.setImageResource(R.drawable.btq_next);
            } else {
                goto_next_lesson.setVisibility(View.GONE);
                back_previous_lesson.setVisibility(View.GONE);
            }
            micro.setTag(MIC_STATE.STATE_SPEAKER);
            micro.setImageResource(R.drawable.ico_speark);
            return;
        }

        drawSentences();

        if (sentences.get(sequence_of_sentences).getAudio_name().equals("")
                && (sequence_of_sentences + 1) <= sentences.size() - 1) {
            sentences.get(sequence_of_sentences).setAudio_name(
                    sentences.get(sequence_of_sentences + 1).getAudio_name());
        }

        if (player == null) {

            player = new MediaPlayer();

            player.setOnCompletionListener(LessonDetailActivity.this);
            player.setOnPreparedListener(LessonDetailActivity.this);
            player.setVolume(1f, 1f);
            player.setLooping(false);

        } else {
            player.reset();
        }

        try {
            FileInputStream stream = new FileInputStream(urlModel.getDir() + "/audio/"
                    + sentences.get(sequence_of_sentences).getAudio_name());

            player.setDataSource(stream.getFD());
            stream.close();
            player.prepare();
        } catch (Exception e) {

        }
    }

    private void drawSentences() {

        TextView tv = new TextView(this);
        // tv.setTextAppearance(this, android.R.style.TextAppearance_Medium);
        tv.setTextSize(17);
        // tv.setTypeface(Typeface.MONOSPACE, Typeface.NORMAL);
        tv.setGravity(Gravity.CENTER_HORIZONTAL);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);

        tv.setBackgroundColor(Color.argb(153, 255, 255, 255));

        if (sentences.get(sequence_of_sentences).getRecognize().equals("TRUE")) {

            if (allowTry)
                return;

            String[] listcontent = sentences.get(sequence_of_sentences).getQuestion_content()
                    .split(regex);

            if (listcontent.length > 0)
                tv.setText(listcontent[0]);

            tv.setTextColor(Color.RED);
            if (sequence_of_sentences >= (sentences.size() - 1)) {
                lp.setMargins(0, 0, 0, 0);
            } else {

                lp.setMargins(0, 0, 0, 25);
            }

        } else {

            tv.setText(sentences.get(sequence_of_sentences).getQuestion_content());
            if (sequence_of_sentences + 1 < sentences.size() - 1) {
                if (!sentences.get(sequence_of_sentences + 1).getRecognize().equals("TRUE")) {
                    tv.setTextColor(Color.BLACK);
                    lp.setMargins(0, 0, 0, 25);

                } else {
                    tv.setTextSize(16);
                    tv.setTextColor(Color.BLACK);
                    lp.setMargins(0, 0, 0, 0);
                }
            } else {
                tv.setTextSize(17);
                tv.setTextColor(Color.BLACK);
                lp.setMargins(0, 0, 0, 0);
            }

        }

        list_sentences_bounder.addView(tv, lp);

        if (sequence_of_sentences + 1 <= sentences.size() - 1) {
            if (!sentences.get(sequence_of_sentences + 1).getRecognize().equals("TRUE")) {

            } else {

                // ///////////////////////////////////////////
                TextView tvextra = new TextView(this);
                // tvextra.setTextAppearance(this,
                // android.R.style.TextAppearance_Medium);
                tvextra.setTextSize(14);
                // tv.setTypeface(Typeface.MONOSPACE, Typeface.NORMAL);
                tvextra.setGravity(Gravity.CENTER_HORIZONTAL);
                tvextra.setText(getString(R.string.let_try));
                tvextra.setTextColor(Color.RED);
                tvextra.setBackgroundColor(Color.argb(153, 255, 255, 255));
                list_sentences_bounder.addView(tvextra, lp);
            }
        } else {
            allowTry = false;
        }
        list_sentences_bounder.post(new Runnable() {

            @Override
            public void run() {
                int dimen = list_sentences_bounder.getMeasuredHeight();
                float scale = getResources().getDisplayMetrics().density;
                double dpval = dimen * 1.0 / scale;

                if (dpval > 120) {
                    scrollview.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollview.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                }

            }
        });
    }

    public boolean hasConnection() {
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected()) {
            return true;
        }

        NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected()) {
            return true;
        }

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            return true;
        }

        return false;
    }

}
